
#include "stdafx.h"
#include "development.h"


//development only code, not compiled in release.

namespace Development
{
	File::File(const char* pPath, Allocator* pAlloc) 
		: mLength(0)
		, mpBuffer(NULL)
		, mpAlloc(pAlloc)
	{
		assert(mpAlloc, "error: require memory");
		HANDLE file = CreateFileA(pPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(file != INVALID_HANDLE_VALUE)
		{
			BY_HANDLE_FILE_INFORMATION info;
			GetFileInformationByHandle(file, &info);
			assert(info.nFileSizeHigh == 0, "error: file too long to buffer");
			
			mpBuffer = (char*)mpAlloc->allocate(info.nFileSizeLow);
			mLength = info.nFileSizeLow;
			
			//todo: factor out the OS stuff, so it's reusable
			unsigned nRead = 0;
			BOOL bReadingOK = true;
			while(nRead < mLength && bReadingOK)
			{
				DWORD nReadThisTime = 0;
				bReadingOK = ReadFile(file, mpBuffer+nRead, mLength-nRead, &nReadThisTime, NULL);
				nRead += nReadThisTime;
			}
		
			if(!bReadingOK) //discard everything read in cases of error
			{	
				mpAlloc->deallocate(mpBuffer);
				mpBuffer = NULL;
				mLength = 0;
			}
		}
		CloseHandle(file);
	}

	File::~File()
	{
		mpAlloc->deallocate(mpBuffer);
	}

};